<?php
namespace app\models;


use yii\base\Model;
use Yii;

/**
 * Signup form
 */

class SignupForm extends Model
{
    public $type;
    public $company_id;
    public $park_id;
    public $name;
    public $identity_card;
    public $idcard_img;
    public $cachet_img;
    /*public $imageFile;
    public $imageFile2;*/


    public $username;




    public function attributeLabels()
    {
        return [
            'type' => '账号类型',
            'name' => '姓名',
            'company_id' => '所属公司',
            'park_id' => '所属园区',
        ];
    }

    /**
     * @inheritdoc
     */

   public function rules()
    {
        return [
            [['type'],'in', 'range' => [1, 2],'message'=>'请选择申请账号类型'],
            [['name','identity_card'], 'checkperson'],
            [['company_id','park_id'],'integer'],
            [['idcard_img','cachet_img'], 'string'],
        ];
    }
    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {

        if ($this->validate()) {
            $userLog = new UserLog();

            $userLog->idcard_img = $this->idcard_img;
            $userLog->cachet_img = $this->cachet_img;
            $userLog->company_id = $this->company_id;
            $userLog->park_id = $this->park_id;
            $userLog->type = $this->type;
            $userLog->idcard = $this->identity_card;
            $userLog->date = time();
            $userLog->status = 1;
            $userLog->psw_tmp=$this->generate_password(8);
            $person= Person::findOne(['company_id'=>$this->company_id,'name'=>$this->name,'identity_card'=>$this->identity_card]);
            $userLog->person_id = $person->id;
            if($userLog->save()){
                return true;
            }else{
                return false;
            }
        }

        return false;
    }


    public function checkperson($attribute,$params){
        $personnum = Person::find()->where(['company_id'=>$this->company_id])->
            andWhere(['name'=>$this->name])->
            andWhere(['identity_card'=>$this->identity_card])->
            count();
        if($personnum == 0){
            $this->addError($attribute, '此人信息不存在，请确认信息正确!');
        }
    }

    function generate_password( $length = 8 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

        return $password;
    }


}
